const Koa = require("Koa"); //引入koa
const parser = require("Koa-parser");//获取post请求数据
const router = require("Koa-router")(); //设置路由
const cors = require("Koa2-cors"); //允许跨域
const app = new Koa();

app.use(cors());
app.use(parser());
app.use(router.routes());

//模拟数据库
const fruitlist = ["香蕉", "苹果", "鸭梨"];

//get方法: 获取水果列表
router.get("/fruits", async ctx => {
    ctx.body = fruitlist;
})
//post 方法: 添加水果
router.post("/fruits", async ctx => {
    let fruit = ctx.request.body.fruit;
    fruitlist.push(fruit);
    ctx.body = true;
})
//delete 方法: 删除水果
router.delete("/fruits/:index", async ctx => {
    let index = ctx.params.index;
    fruitlist.splice(index, 1);
    ctx.body = true;
})

app.listen(3000, () => { 
    console.log("sever is running");
})